import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/rendering.dart';
import 'verification_item.dart';

// 验证码输入框
class VerificationBox extends StatefulWidget {
  VerificationBox(
      {this.maxLength = 6,
      this.width = 45,
      this.height = 45,
      this.onChanged,
      this.type = VerificationItemType.box,
      this.decoration,
      this.textStyle,
      this.unfocus = true,
      this.inputFormatters,
      this.autoFocus = true,

      this.showCursor = true,
      this.cursorColor,
      this.cursorWidth,
      this.cursorDecoration});

  // 几位验证码，一般6位，还有4位的
  final int maxLength;

  // 每一个item的宽高
  final double width;
  final double height;

  // 输入完成回调
  final ValueChanged onChanged;

  // 每个item的装饰类型，[VerificationItemType]
  final VerificationItemType type;

  // 每个item的样式
  final Decoration decoration;

  // 光标颜色
  final Decoration cursorDecoration;
  final Color cursorColor;
  final double cursorWidth;
  final bool showCursor;
  // 是否自动获取焦点
  final bool autoFocus;
  // 输入完成后是否失去焦点，默认true，失去焦点后，软键盘消失
  final bool unfocus;

  // 文本样式
  final TextStyle textStyle;

  final List<TextInputFormatter> inputFormatters;

  @override
  State<StatefulWidget> createState() => _VerificationBox();
}

class _VerificationBox extends State<VerificationBox> {
  final GlobalKey<EditableTextState> myEditableTextKey =
      GlobalKey<EditableTextState>();

  TextEditingController _controller;
  FocusNode _focusNode;
  List _contentList = [];

  @override
  void initState() {
    List.generate(widget.maxLength, (index) {
      _contentList.add('');
    });
    _controller = TextEditingController();
    _focusNode = FocusNode();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        FocusScope.of(context).requestFocus(_focusNode);
      },
      child: Stack(
        children: <Widget>[
          _textField(),
          Positioned.fill(
              child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: List.generate(widget.maxLength, (index) {
                bool _showCursor = widget.showCursor && (_controller.text.length == index);
                return VerificationItem(
                    text: _contentList[index],
                    type: widget.type,
                    width: widget.width,
                    height: widget.height,
                    textStyle: widget.textStyle,
                    showCursor: _showCursor,
                    decoration: widget.decoration,
                    cursorColor: widget.cursorColor,
                    cursorWidth: widget.cursorWidth,
                    cursorDecoration: widget.cursorDecoration);
              })))
        ],
      ),
    );
  }

  // 构建TextField
  _textField() {
    return TextField(
          key: myEditableTextKey,
          controller: _controller,
          decoration: InputDecoration(
            border: UnderlineInputBorder(
                borderSide: BorderSide(width: 3, color: Colors.white24)),
            enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.transparent)),
            focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.transparent)),
          ),
          style: TextStyle(color: Colors.transparent),
          buildCounter: (
            BuildContext context, {
            int currentLength,
            int maxLength,
            bool isFocused,
          }) {
            return Text('');
          },
          maxLength: widget.maxLength,
          mouseCursor: MouseCursor.defer, // TextField will
          inputFormatters: widget.inputFormatters,
          restorationId: 'editable',
          cursorColor: Colors.transparent,
          focusNode: _focusNode,
          autofocus: widget.autoFocus,
          showCursor: false,
          onChanged: _onChanged,
        );
  }

  _onChanged(String value) {
    for (int i = 0; i < widget.maxLength; i++) {
      if (i < value.length) {
        _contentList[i] = value.substring(i, i + 1);
      } else {
        _contentList[i] = '';
      }
    }
    if (value.length == widget.maxLength) {
      _focusNode.unfocus();
      if (widget.onChanged != null) {
        widget.onChanged(value);
      }
    }
    setState(() {});
  }
}
